const express = require("express")
const router = express.Router()

const {success, failure} = require("../utils/response")
const {BadRequest} = require("http-errors")

const {singleImageUpload, singleVideoUpload} = require("../utils/upload")

/**
 * 上传图片
 */
router.post("/image", (req, res) => {
    singleImageUpload(req, res, async (err) => {
        if(err) {
            return failure(res, err)
        }
        if(!req.file) {
            return failure(res, new BadRequest("请选择要上传的文件"))
        }
        const path = `/uploads/images/${req.file.filename}`

        success(res, "上传成功", {
            image: path,
            imageUrl: `${process.env.HOST}:${process.env.PORT}${path}`
        })
    })
})

/**
 * 上传视频
 */
router.post("/video", (req, res) => {
    singleVideoUpload(req, res, async (err) => {
        console.log(err)
        if(err) {
            return failure(res, err)
        }
        if(!req.file) {
            return failure(res, new BadRequest("请选择要上传的文件"))
        }

        const path = `/uploads/videos/${req.file.filename}`

        success(res, "上传成功", {
            image: path,
            imageUrl: `${process.env.HOST}:${process.env.PORT}${path}`
        })
    })
})

module.exports = router